package com.yuexunit.finance.system.action.v1;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.account.entity.AccountNameEntity;
import com.yuexunit.account.entity.AccountSessionEntity;
import com.yuexunit.account.service.AccountService;
import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.common.util.HttpUtils;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.context.LoginActionFinanceImpl;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEvaluationEntity;
import com.yuexunit.finance.member.entity.FingerTrunkAccountMappingEntity;
import com.yuexunit.finance.member.entity.lexicon.AuditStateEnum;
import com.yuexunit.finance.member.service.EnterpriseGradeEvaluationService;
import com.yuexunit.finance.member.service.EnterpriseGradeService;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.member.service.FingerTrunkAccountMappingService;
import com.yuexunit.finance.project.FinanceQRCodeService;
import com.yuexunit.finance.project.action.v1.FinanceLoanActionApi;
import com.yuexunit.finance.project.action.v1.model.output.ChangeLocationResult;
import com.yuexunit.finance.project.action.v1.model.output.FinanceWriteoffLineInfo;
import com.yuexunit.finance.project.entity.AccountTerminalEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.FinanceQRCodeEntity;
import com.yuexunit.finance.project.entity.PickupBulkstockWarehouseEntity;
import com.yuexunit.finance.project.entity.RankingListEntity;
import com.yuexunit.finance.project.entity.lexicon.BeneficiaryMethodEnum;
import com.yuexunit.finance.project.service.AccountTerminalService;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.FinanceMoneyStatementService;
import com.yuexunit.finance.project.service.PickupBulkstockWarehouseService;
import com.yuexunit.finance.project.service.RankingListService;
import com.yuexunit.finance.statistics.action.v1.model.CostInfoDetail;
import com.yuexunit.finance.system.action.v1.dto.LonsMoneyInfoCastor;
import com.yuexunit.finance.system.action.v1.dto.SystemParamDetailCastor;
import com.yuexunit.finance.system.action.v1.model.BlankInfoDetail;
import com.yuexunit.finance.system.action.v1.model.CapitalDetail;
import com.yuexunit.finance.system.action.v1.model.CommonResonInfo;
import com.yuexunit.finance.system.action.v1.model.DataSourceDetail;
import com.yuexunit.finance.system.action.v1.model.FinanceFilesNorm;
import com.yuexunit.finance.system.action.v1.model.FinanceLetterDetail;
import com.yuexunit.finance.system.action.v1.model.LendUnitInfoDetail;
import com.yuexunit.finance.system.action.v1.model.LoansMoneyInfoParam;
import com.yuexunit.finance.system.action.v1.model.LoansMoneyInfoParamDetail;
import com.yuexunit.finance.system.action.v1.model.LoansMoneyRecord;
import com.yuexunit.finance.system.action.v1.model.LoansMoneyReturnInfo;
import com.yuexunit.finance.system.action.v1.model.RankingListDetail;
import com.yuexunit.finance.system.action.v1.model.SessionDetail;
import com.yuexunit.finance.system.action.v1.model.ShipInfo;
import com.yuexunit.finance.system.action.v1.model.SystemBlankDetail;
import com.yuexunit.finance.system.action.v1.model.SystemParamDetail;
import com.yuexunit.finance.system.action.v1.model.UpdateInfo;
import com.yuexunit.finance.system.action.v1.model.UserActiveCardInfoDetail;
import com.yuexunit.finance.system.action.v1.model.UserCardInfoDetail;
import com.yuexunit.finance.system.action.v1.model.UserCardTypeInfoDetail;
import com.yuexunit.finance.system.entity.CapitalAccountInfoEntity;
import com.yuexunit.finance.system.entity.CostInfoEntity;
import com.yuexunit.finance.system.entity.DataSourceEntity;
import com.yuexunit.finance.system.entity.FinanceFilesNormEntity;
import com.yuexunit.finance.system.entity.FinanceLetterEntity;
import com.yuexunit.finance.system.entity.LendUnitInfoEntity;
import com.yuexunit.finance.system.entity.LoansMoneyInfoEntity;
import com.yuexunit.finance.system.entity.LoansMoneyRecordInfoEntity;
import com.yuexunit.finance.system.entity.SystemParamEntity;
import com.yuexunit.finance.system.entity.UserActiveCardInfoEntity;
import com.yuexunit.finance.system.entity.UserCardInfoEntity;
import com.yuexunit.finance.system.entity.UserCardTypeInfoEntity;
import com.yuexunit.finance.system.entity.lexicon.CardStatusEnum;
import com.yuexunit.finance.system.entity.lexicon.FinancingChannelEnum;
import com.yuexunit.finance.system.entity.lexicon.OperateTypeEnum;
import com.yuexunit.finance.system.entity.lexicon.ParamTypeEnum;
import com.yuexunit.finance.system.service.BankInfoService;
import com.yuexunit.finance.system.service.CostInfoService;
import com.yuexunit.finance.system.service.DataSourceService;
import com.yuexunit.finance.system.service.FinanceFilesNormService;
import com.yuexunit.finance.system.service.FinanceLetterService;
import com.yuexunit.finance.system.service.LendUnitInfoService;
import com.yuexunit.finance.system.service.LoansMoneyInfoService;
import com.yuexunit.finance.system.service.LoansMoneyRecordService;
import com.yuexunit.finance.system.service.SystemParamService;
import com.yuexunit.finance.system.service.UserActiveCardInfoService;
import com.yuexunit.finance.system.service.UserCardInfoService;
import com.yuexunit.finance.system.service.UserCardTypeService;
import com.yuexunit.fs.action.InquireFileAction;
import com.yuexunit.fs.action.dto.DeleteFileActionInput;
import com.yuexunit.fs.action.dto.InquireFileOutput;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferServiceImpl;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.jsonutil.JSON;
import com.yuexunit.organization.entity.OrgREmpEntity;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;
import com.yuexunit.util.UuidUtil;

/**
 * @author wenwenlong
 */
@Implements(SystemParamActionApi.class)
public class SystemParamActionApiImpl implements SystemParamActionApi {

	private SystemParamService systemParamService = ComponentFactory.loadClass(SystemParamService.class);
	private CostInfoService costinfoService = ComponentFactory.loadClass(CostInfoService.class);
	private BankInfoService bankInfoService = ComponentFactory.loadClass(BankInfoService.class);
	private LendUnitInfoService lendUnitInfoService = ComponentFactory.loadClass(LendUnitInfoService.class);
	private LoansMoneyInfoService loansMoneyInfoService = ComponentFactory.loadClass(LoansMoneyInfoService.class);
	private LoansMoneyRecordService loansMoneyRecordService = ComponentFactory.loadClass(LoansMoneyRecordService.class);
	private FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);
	private UserCardTypeService userCardTypeService = ComponentFactory.loadClass(UserCardTypeService.class);
	private UserCardInfoService userCardInfoService = ComponentFactory.loadClass(UserCardInfoService.class);
	private UserActiveCardInfoService userActiveCardInfoService = ComponentFactory.loadClass(UserActiveCardInfoService.class);
	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
	private EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);
	private EnterpriseGradeEvaluationService enterpriseGradeEvaluationService = ComponentFactory.loadClass(EnterpriseGradeEvaluationService.class);
	private DataSourceService dataSourceService = ComponentFactory.loadClass(DataSourceService.class);
	private AccountService accountService = ComponentFactory.loadClass(AccountService.class);
	private FinanceLoanActionApi financeLoanActionApi = ComponentFactory.loadClass(FinanceLoanActionApi.class);
	private FinanceQRCodeService financeQRCodeService = ComponentFactory.loadClass(FinanceQRCodeService.class);
	private FingerTrunkAccountMappingService fingerTrunkAccountMappingService = ComponentFactory.loadClass(FingerTrunkAccountMappingService.class);
	private RankingListService rankingListService = ComponentFactory.loadClass(RankingListService.class);
	private FinanceLetterService financeLetterService = ComponentFactory.loadClass(FinanceLetterService.class);
	private FinanceFilesNormService financeFilesNormService = ComponentFactory.loadClass(FinanceFilesNormService.class);
	private AccountTerminalService accountTerminalService = ComponentFactory.loadClass(AccountTerminalService.class);
	private ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
	private PickupBulkstockWarehouseService pickupBulkstockWarehouseService = ComponentFactory.loadClass(PickupBulkstockWarehouseService.class);
	public static Logger logger = LoggerFactory.getLogger(SystemParamActionApiImpl.class);

	@Override
	public Long createSystemParam(SystemParamDetail params) {
		SystemParamEntity entity = SystemParamDetailCastor.toSystemParamEntity(params);
		return systemParamService.createSytemParam(entity);
	}

	@Override
	public void updateSystemParam(SystemParamDetail paramDetail) {
		SystemParamEntity entity = SystemParamDetailCastor.toSystemParamEntity(paramDetail);
		systemParamService.updateSytemParam(entity);
	}

	@Override
	public SystemParamDetail inquireSystemParam(Long paramId) {
		SystemParamEntity entity = systemParamService.inquireSytemParamDetail(paramId);
		return SystemParamDetailCastor.toSystemParamDetail(entity);
	}

	@Override
	public PageList<SystemParamDetail> inquireSystemParamList(String paramName, Integer paramType, PageCriteria page) {
		PageList<SystemParamEntity> entityList = systemParamService.inquireSystemParamList(paramName, ParamTypeEnum.valueOf(paramType), page);
		return changeToDetailList(page, entityList);
	}

	private PageList<SystemParamDetail> changeToDetailList(PageCriteria page, PageList<SystemParamEntity> entityList) {
		PageList<SystemParamDetail> detailList = new PageList<SystemParamDetail>(page, entityList.getTotalRecordCount());
		for (SystemParamEntity entity : entityList) {
			detailList.add(SystemParamDetailCastor.toSystemParamDetail(entity));
		}
		return detailList;
	}

	@Override
	public SystemBlankDetail inquireSystemBlankInfo() {
		SystemBlankDetail blank = new SystemBlankDetail();
		SystemParamEntity param = systemParamService.inquireSytemParamDetail(5L);
		blank.setDepositBank(param.getParamValue());
		param = systemParamService.inquireSytemParamDetail(6L);
		blank.setAccountHolder(param.getParamValue());
		param = systemParamService.inquireSytemParamDetail(7L);
		blank.setCreditCard(param.getParamValue());
		return blank;
	}

	@Override
	public String inquireSystemParamByName(String paramName) {
		try {
			paramName = URLDecoder.decode(paramName, "utf-8");
			return systemParamService.inquireSytemParamDetailByName(paramName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<CommonResonInfo> inquireCommonSelectorList(Long resonType) {
		if (resonType == null) {
			resonType = 8L;
		}
		List<CommonResonInfo> resons = new ArrayList<>();
		SystemParamEntity param = systemParamService.inquireSytemParamDetail(resonType);
		String[] split = param.getParamValue().split(",");
		for (int i = 0; i < split.length; i++) {
			CommonResonInfo reson = new CommonResonInfo();
			reson.setIndex(i + 1);
			reson.setReson(split[i]);
			resons.add(reson);
		}
		return resons;
	}

	@Override
	public String createCostInfo(String costInfoNumber, String costInfoType, String costInfoRemark) {
		CostInfoEntity entity = new CostInfoEntity();
		entity.setCostInfoNumber(costInfoNumber);
		entity.setCostInfoRemark(costInfoRemark);
		entity.setCostInfoType(costInfoType);
		costinfoService.createCostInfo(entity);
		return entity.getCostInfoId().toString();
	}

	@Override
	public void disableCostInfo(Long costInfoId) {
		costinfoService.disableCostInfo(costInfoId);
	}

	@Override
	public PageList<CostInfoDetail> inquireCostInfoPagelist(String costInfoNumber, String costInfoType, PageCriteria page) {
		PageList<CostInfoEntity> list = costinfoService.ipuireCostInfoList(costInfoNumber, costInfoType, page);
		PageList<CostInfoDetail> details = new PageList<> (page, list.getTotalRecordCount());
		for (CostInfoEntity cie : list) {
			CostInfoDetail detail = new CostInfoDetail();
			BeanUtils.copyProperties(cie, detail);
			details.add(detail);
		}
		return details;
	}

	@Override
	public String createBlankInfo(String accountBank, String accountBankCard, String accountBnakName, BigDecimal balance, String remark) {
		CapitalAccountInfoEntity entity = new CapitalAccountInfoEntity();
		entity.setAccountLoan(BigDecimal.ZERO);
		entity.setAccountBank(accountBank);
		entity.setAccountBankCard(accountBankCard);
		entity.setAccountBankName(accountBnakName);
		entity.setRemark(remark);
		if (balance == null) {
			entity.setAccountBalance(BigDecimal.ZERO);
			entity.setAccountAmount(BigDecimal.ZERO);
		} else {
			entity.setAccountBalance(balance);
			entity.setAccountAmount(balance);
		}
		bankInfoService.createBankInfo(entity);
		return entity.getAccountInfoId().toString();
	}

	@Override
	public void updateBlankInfo(Long accountInfoId, String accountBank, String accountBankCard, String accountBankName, BigDecimal balance, String remark) {
		CapitalAccountInfoEntity entity = bankInfoService.inquireBankInfoDetail(accountInfoId);
		entity.setAccountBank(accountBank);
		entity.setAccountBankCard(accountBankCard);
		entity.setAccountBankName(accountBankName);
		entity.setRemark(remark);
		if (balance == null) {
			entity.setAccountBalance(BigDecimal.ZERO);
		} else {
			entity.setAccountBalance(balance);
			entity.setAccountAmount(balance);
		}
		bankInfoService.updateBankInfo(entity);
	}

	@Override
	public PageList<BlankInfoDetail> inquireBlankInfoPagelist(String accountBank, String accountBankCard, String accountBankName, PageCriteria page) {
		PageList<CapitalAccountInfoEntity> results = bankInfoService.inquireBankInfoPageList(accountBank, accountBankCard, accountBankName, page);
		PageList<BlankInfoDetail> list = new PageList<>(page, results.getTotalRecordCount());

		for (CapitalAccountInfoEntity result : results) {
			BlankInfoDetail detail = new BlankInfoDetail();
			BeanUtils.copyProperties(result, detail);
			list.add(detail);
		}
		return list;
	}

	@Override
	public void topBlankInfo(Long accountInfoId) {
		CapitalAccountInfoEntity entity = bankInfoService.inquireBankInfoDetail(accountInfoId);
		entity.setTop(Boolean.TRUE);
		bankInfoService.updateBankInfo(entity);
	}

	@Override
	public void cancelTopBlankInfo(Long accountInfoId) {
		CapitalAccountInfoEntity entity = bankInfoService.inquireBankInfoDetail(accountInfoId);
		entity.setTop(Boolean.FALSE);
		bankInfoService.updateBankInfo(entity);
	}

	@Override
	public BlankInfoDetail inquireBlankInfoDetail(Long accountInfoId) {
		CapitalAccountInfoEntity entity = bankInfoService.inquireBankInfoDetail(accountInfoId);
		BlankInfoDetail detail = new BlankInfoDetail();
		BeanUtils.copyProperties(entity, detail);
		return detail;
	}


	@Override
	public CapitalDetail inquireCapitalDetail() {
		CapitalDetail detail = new CapitalDetail();
		detail.setAccountAmount(BigDecimal.ZERO);
		detail.setAccountBalance(BigDecimal.ZERO);
		detail.setAccountLoan(BigDecimal.ZERO);
		List<CapitalAccountInfoEntity> caies = bankInfoService.inquireBankInfoList();
		for (CapitalAccountInfoEntity caie : caies) {
			detail.setAccountAmount(detail.getAccountAmount().add(caie.getAccountAmount()));
			detail.setAccountBalance(detail.getAccountBalance().add(caie.getAccountBalance()));
			detail.setAccountLoan(detail.getAccountLoan().add(caie.getAccountLoan()));
			detail.getCapitalValues().add(caie.getAccountAmount());
			detail.getCapitalKeys().add(caie.getAccountBankName());
		}

		PageCriteria page = PageCriteria.defaultInstance();
		page.setPageSize(10000);
		List<FinanceWriteoffLineInfo> dfwlis = financeLoanActionApi.inquireDisbursementWriteoffPageList(null, DateUtils.addDateField(DateUtil.now(), Calendar.YEAR, -1), DateUtil.now(), null, null, page);
		String tmp1 = "";
		String tmp2 = "";
		Calendar cal = Calendar.getInstance();
		Calendar cal1 = Calendar.getInstance();
		for (FinanceWriteoffLineInfo dfwli : dfwlis) {
			cal.setTime(dfwli.getOperateDateTime());
			if (!tmp1.equals(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1))) {
				tmp1 = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
				detail.getdDate().add(tmp1);
				detail.getdAmount().add(dfwli.getWriteoffAmount());
			} else {
				detail.getdAmount().set(detail.getdAmount().size() - 1, detail.getdAmount().get(detail.getdAmount().size() - 1).add(dfwli.getWriteoffAmount()));
			}
		}
		List<FinanceWriteoffLineInfo> rfwlis = financeLoanActionApi.inquireReceiptWriteoffPageList(null, DateUtils.addDateField(DateUtil.now(), Calendar.YEAR, -1), DateUtil.now(), null, null, page);
		tmp1 = "";
		for (FinanceWriteoffLineInfo rfwli : rfwlis) {
			cal.setTime(rfwli.getOperateDateTime());
			if (!tmp1.equals(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1))) {
				tmp1 = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
				detail.getrDate().add(tmp1);
				detail.getrAmount().add(rfwli.getWriteoffAmount());
			} else {
				detail.getrAmount().set(detail.getrAmount().size() - 1, detail.getrAmount().get(detail.getrAmount().size() - 1).add(rfwli.getWriteoffAmount()));
			}
		}
		cal = Calendar.getInstance();
		for (int i = 0; i < 12; i++) {
			cal.setTime(DateUtils.addDateField(DateUtil.now(), Calendar.MONTH, i-12));
			tmp1 = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
			detail.getDates().add(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1));
			detail.getReceives().add(BigDecimal.ZERO);
			detail.getPayments().add(BigDecimal.ZERO);

			for (FinanceWriteoffLineInfo rfwli : rfwlis) {
				cal1.setTime(rfwli.getOperateDateTime());
				tmp2 = cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) + 1);
				if (tmp1.equals(tmp2)) {
					detail.getReceives().set(i, detail.getReceives().get(i).add(rfwli.getWriteoffAmount()));
				}
			}

			for (FinanceWriteoffLineInfo dfwli : dfwlis) {
				cal1.setTime(dfwli.getOperateDateTime());
				tmp2 = cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) + 1);
				if (tmp1.equals(tmp2)) {
					detail.getPayments().set(i, detail.getPayments().get(i).add(dfwli.getWriteoffAmount()));
				}
			}
			detail.getNetInflow().add(detail.getReceives().get(i).subtract(detail.getPayments().get(i)));

		}

		return detail;
	}

	@Override
	public String createLendUnitInfo(String lendUnitName, String lendUnitBank, String lendUnitBankCard, String lendUnitBankName) {
		LendUnitInfoEntity entity = new LendUnitInfoEntity();
		entity.setLendUnitName(lendUnitName);
		entity.setLendUnitBank(lendUnitBank);
		entity.setLendUnitBankCard(lendUnitBankCard);
		entity.setLendUnitBankName(lendUnitBankName);
		lendUnitInfoService.createLendUnitInfo(entity);
		return entity.getLendUnitId().toString();
	}

	@Override
	public void updateLendUnitInfo(Long lendUnitId, String lendUnitName, String lendUnitBank, String lendUnitBankCard, String lendUnitBankName) {
		LendUnitInfoEntity entity = lendUnitInfoService.inquireLendUnitInfoDetail(lendUnitId);
		entity.setLendUnitName(lendUnitName);
		entity.setLendUnitBank(lendUnitBank);
		entity.setLendUnitBankCard(lendUnitBankCard);
		entity.setLendUnitBankName(lendUnitBankName);
		lendUnitInfoService.updateLendUnitInfo(entity);
	}

	@Override
	public PageList<LendUnitInfoDetail> inquireLendUnitInfoPagelist(String lendUnitName, String lendUnitBank, String lendUnitBankCard, String lendUnitBankName,
			PageCriteria page) {
		PageList<LendUnitInfoEntity> pages = lendUnitInfoService.inquireLendUnitInfoPagelist(lendUnitName, lendUnitBank, lendUnitBankCard, lendUnitBankName, page);
		PageList<LendUnitInfoDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (LendUnitInfoEntity lue : pages) {
			LendUnitInfoDetail detail = new LendUnitInfoDetail();
			BeanUtils.copyProperties(lue, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public List<LendUnitInfoDetail> inquireLendUnitInfoList(String lendUnitName, String lendUnitBank, String lendUnitBankCard, String lendUnitBankName) {
		List<LendUnitInfoEntity> pages = lendUnitInfoService.inquireLendUnitInfoList(lendUnitName, lendUnitBank, lendUnitBankCard, lendUnitBankName);
		List<LendUnitInfoDetail> results = new ArrayList<>();
		for (LendUnitInfoEntity lue : pages) {
			LendUnitInfoDetail detail = new LendUnitInfoDetail();
			BeanUtils.copyProperties(lue, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public LendUnitInfoDetail inquireLendUnitInfoDetail(Long lendUnitId) {
		LendUnitInfoEntity entity = lendUnitInfoService.inquireLendUnitInfoDetail(lendUnitId);
		LendUnitInfoDetail detail = new LendUnitInfoDetail();
		BeanUtils.copyProperties(entity, detail);
		return detail;
	}

	@Override
	public void stopLendUnitInfoDetail(Long lendUnitId) {
		LendUnitInfoEntity entity = lendUnitInfoService.inquireLendUnitInfoDetail(lendUnitId);
		entity.setEnabled(Boolean.FALSE);
		lendUnitInfoService.updateLendUnitInfo(entity);
	}

	@Override
	public void useLendUnitInfoDetail(Long lendUnitId) {
		LendUnitInfoEntity entity = lendUnitInfoService.inquireLendUnitInfoDetail(lendUnitId);
		entity.setEnabled(Boolean.TRUE);
		lendUnitInfoService.updateLendUnitInfo(entity);
	}

	@Override
	@Transactional
	public String createLonsMoneyInfo(LoansMoneyInfoParam param) {
		LoansMoneyInfoEntity entity = new LoansMoneyInfoEntity();
		BeanUtils.copyProperties(param, entity);
		entity.setPayment(BeneficiaryMethodEnum.valueOf(param.getPayment()));
		entity.setChannel(FinancingChannelEnum.valueOf(param.getChannel()));
		entity.setAmount(param.getAmount());
		entity.setConfirmState(Boolean.FALSE);

		Calendar cal = Calendar.getInstance();
		cal.setTime(param.getBorrowedDateCount());
		if (param.getTimeLimitUnit().equals("年")) {
			cal.add(Calendar.YEAR, param.getTimeLimit());
		} else if (param.getTimeLimitUnit().equals("月")){
			cal.add(Calendar.MONTH, param.getTimeLimit());
		} else if (param.getTimeLimitUnit().equals("日")){
			cal.add(Calendar.DATE, param.getTimeLimit());
		}
		entity.setEffectiveDate(cal.getTime());

		loansMoneyInfoService.createLoansMoney(entity);

		LoansMoneyRecordInfoEntity record = new LoansMoneyRecordInfoEntity();
		record.setAmount(param.getAmount());
		record.setOperateTime(DateUtil.now());
		record.setOperator(FinanceSessionContext.getAccountFullName());
		record.setOperateType(OperateTypeEnum.CREATE);
		record.setLonasMoneyId(entity.getLoansMoneyId());
		loansMoneyRecordService.createLoansMoneyRecord(record);

		return entity.getLoansMoneyId().toString();
	}

	@Override
	@Transactional
	public void confirmLonsMoneyInfoDetail(Long loansMoneyId) {
		LoansMoneyInfoEntity entity = loansMoneyInfoService.inquireLoansMoneyDetail(loansMoneyId);
		entity.setConfirmState(Boolean.TRUE);

		// 生成流水
		FinanceMoneyStatementEntity moneyEntity = LonsMoneyInfoCastor.fromLoansMoenyInfo(entity, null);
		financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
		loansMoneyInfoService.updateLoansMoney(entity);
	}

	@Override
	public void deletLonsMoneyInfoDetail(Long loansMoneyId) {
		LoansMoneyInfoEntity entity = loansMoneyInfoService.inquireLoansMoneyDetail(loansMoneyId);
		if (entity.getConfirmState()) {
			throw new BusinessException("已确认的融资不可删除！");
		}
		loansMoneyInfoService.deleteMoneyDetail(entity.getLoansMoneyId());
	}

	@Override
	@Transactional
	public void additionLonsMoneyInfo(Long loansMoneyId, BigDecimal amount, Date date, String additionReason, String remark) {
		LoansMoneyInfoEntity entity = loansMoneyInfoService.inquireLoansMoneyDetail(loansMoneyId);
		entity.setAmount(entity.getAmount().add(amount));

		LoansMoneyRecordInfoEntity record = new LoansMoneyRecordInfoEntity();
		record.setAmount(amount);
		record.setOperateTime(DateUtil.now());
		record.setOperator(FinanceSessionContext.getAccountFullName());
		record.setOperateType(OperateTypeEnum.ADDITION);
		record.setLonasMoneyId(entity.getLoansMoneyId());
		record.setRemark(remark);
		record.setAdditionReason(additionReason);
		loansMoneyRecordService.createLoansMoneyRecord(record);

		// 生成流水
		FinanceMoneyStatementEntity moneyEntity = LonsMoneyInfoCastor.fromLoansMoenyInfo(entity, record);
		financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
	}

	@Override
	@Transactional
	public void returnLonsMoneyInfo(Long loansMoneyId, BigDecimal amount, Date date, String remark) {
		LoansMoneyInfoEntity entity = loansMoneyInfoService.inquireLoansMoneyDetail(loansMoneyId);
		entity.setAmount(entity.getAmount().subtract(amount));

		LoansMoneyRecordInfoEntity record = new LoansMoneyRecordInfoEntity();
		record.setAmount(amount);
		record.setOperateTime(DateUtil.now());
		record.setOperator(FinanceSessionContext.getAccountFullName());
		record.setOperateType(OperateTypeEnum.RETURN);
		record.setLonasMoneyId(entity.getLoansMoneyId());
		record.setRemark(remark);
		loansMoneyRecordService.createLoansMoneyRecord(record);

		// 生成流水
		FinanceMoneyStatementEntity moneyEntity = LonsMoneyInfoCastor.fromReturnLoansMoenyInfo(entity, record);
		financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
	}

	@Override
	public LoansMoneyInfoParamDetail inquireLonsMoneyInfoDetail(Long loansMoneyId) {
		LoansMoneyInfoParamDetail detail = new LoansMoneyInfoParamDetail();
		LoansMoneyInfoEntity entity = loansMoneyInfoService.inquireLoansMoneyDetail(loansMoneyId);
		LendUnitInfoEntity lend = lendUnitInfoService.inquireLendUnitInfoDetail(entity.getLendUnitId());
		BeanUtils.copyProperties(entity, detail);
		detail.setPayment(entity.getPayment().ordinal());
		detail.setChannel(entity.getChannel().ordinal());
		detail.setLendUnitName(lend.getLendUnitName());
		return detail;
	}

	@Override
	public PageList<LoansMoneyInfoParamDetail> inquireLonsMoneyInfoList(String lendUnitName, Date startDate, String financialBatch, String financingBatch,
			Date endDate, Boolean confirmState, PageCriteria page) {
		List<LendUnitInfoEntity> lends = lendUnitInfoService.inquireLendUnitInfoList(lendUnitName);
		List<Long> lendUnitIds = new ArrayList<>();
		for (LendUnitInfoEntity lendUnitInfoEntity : lends) {
			lendUnitIds.add(lendUnitInfoEntity.getLendUnitId());
		}
		if (StringUtil.isNotBlank(lendUnitName) && lendUnitIds.isEmpty()) {
			return null;
		}
		PageList<LoansMoneyInfoEntity> pages = loansMoneyInfoService.inquireLoansMoneyPageList(lendUnitIds, startDate, endDate, financialBatch, financingBatch, confirmState, page);
		PageList<LoansMoneyInfoParamDetail> params = new PageList<LoansMoneyInfoParamDetail>(page, pages.getTotalRecordCount());
		for (LoansMoneyInfoEntity loansMoneyInfoEntity : pages) {
			LendUnitInfoEntity lend = lendUnitInfoService.inquireLendUnitInfoDetail(loansMoneyInfoEntity.getLendUnitId());
			LoansMoneyInfoParamDetail p = new LoansMoneyInfoParamDetail();
			BeanUtils.copyProperties(loansMoneyInfoEntity, p);
			p.setChannel(loansMoneyInfoEntity.getChannel().ordinal());
			p.setPayment(loansMoneyInfoEntity.getPayment().ordinal());
			p.setLendUnitName(lend.getLendUnitName());
			params.add(p);
		}
		return params;
	}

	@Override
	public PageList<LoansMoneyRecord> inquireLonsMoneyRecordPageList(Long loansMoneyId, PageCriteria page) {
		PageList<LoansMoneyRecordInfoEntity> pages = loansMoneyRecordService.inquireLoansMoneyReordPageList(loansMoneyId, page);
		PageList<LoansMoneyRecord> results = new PageList<LoansMoneyRecord>(page, pages.getTotalRecordCount());
		for (LoansMoneyRecordInfoEntity lre : pages) {
			LoansMoneyRecord record = new LoansMoneyRecord();
			BeanUtils.copyProperties(lre, record);
			record.setOperateType(lre.getOperateType().ordinal());
			results.add(record);
		}
		return results;
	}

	@Override
	public LoansMoneyReturnInfo calLonsMoney(Long loansMoneyId, Date cutoffDate) {
		LoansMoneyReturnInfo info = new LoansMoneyReturnInfo();
		LoansMoneyInfoEntity entity = loansMoneyInfoService.inquireLoansMoneyDetail(loansMoneyId);
		info.setCommission(entity.getCommission());
		info.setInterest(entity.getInterestRate().divide(new BigDecimal(365), 4).multiply(entity.getAmount()).multiply(new BigDecimal(0.01)).multiply(new BigDecimal(DateUtils.daysBetween(entity.getBorrowedDateCount(), cutoffDate))));
		info.setPoundage(entity.getPoundage());
		info.setPrincipal(entity.getAmount());
		info.setSummation(info.getCommission().add(info.getInterest().add(info.getPoundage()).add(info.getPrincipal())));
		return info;
	}

	@Override
	public String createUserCardType(String cardTypeName, BigDecimal rateDiscount, BigDecimal punishDiscount, Integer exceedDayDiscount,
			Integer disposeDayDiscount, BigDecimal integeralPower) {
		UserCardTypeInfoEntity entity = new UserCardTypeInfoEntity();
		entity.setCardTypeName(cardTypeName);
		entity.setRateDiscount(rateDiscount);
		entity.setPunishDiscount(punishDiscount);
		entity.setExceedDayDiscount(exceedDayDiscount);
		entity.setDisposeDayDiscount(disposeDayDiscount);
		entity.setIntegeralPower(integeralPower);
		userCardTypeService.createUserCardType(entity);
		return entity.getCardTypeId().toString();
	}

	@Override
	public void updateUserCardType(Long cardTypeId, String cardTypeName, BigDecimal rateDiscount, BigDecimal punishDiscount, Integer exceedDayDiscount,
			Integer disposeDayDiscount, BigDecimal integeralPower) {
		UserCardTypeInfoEntity entity = userCardTypeService.inquireCardTypeDetail(cardTypeId);
		entity.setCardTypeName(cardTypeName);
		entity.setRateDiscount(rateDiscount);
		entity.setPunishDiscount(punishDiscount);
		entity.setExceedDayDiscount(exceedDayDiscount);
		entity.setDisposeDayDiscount(disposeDayDiscount);
		entity.setIntegeralPower(integeralPower);
		userCardTypeService.updateUserCardType(entity);
	}

	@Override
	public void disableCardType(Long cardTypeId) {
		userCardTypeService.disableUserCardType(cardTypeId);
	}

	@Override
	public void enableCardType(Long cardTypeId) {
		userCardTypeService.enableUserCardType(cardTypeId);
	}

	@Override
	public UserCardTypeInfoDetail inquireCardTypeDetail(Long cardTypeId) {
		UserCardTypeInfoEntity entity = userCardTypeService.inquireCardTypeDetail(cardTypeId);
		UserCardTypeInfoDetail detail = new UserCardTypeInfoDetail();
		BeanUtils.copyProperties(entity, detail);
		return detail;
	}

	@Override
	public PageList<UserCardTypeInfoDetail> inquireCardTypePageList(PageCriteria page) {
		PageList<UserCardTypeInfoEntity> lists = userCardTypeService.inquireCardTypePageList(page);
		PageList<UserCardTypeInfoDetail> results = new PageList<UserCardTypeInfoDetail>(page, lists.getTotalRecordCount());
		for (UserCardTypeInfoEntity uctie : lists) {
			UserCardTypeInfoDetail detail = new UserCardTypeInfoDetail();
			BeanUtils.copyProperties(uctie, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public List<UserCardTypeInfoDetail> inquireCardTypeList() {
		List<UserCardTypeInfoEntity> lists = userCardTypeService.inquireCardTypeList();
		List<UserCardTypeInfoDetail> results = new ArrayList<UserCardTypeInfoDetail>();
		for (UserCardTypeInfoEntity uctie : lists) {
			UserCardTypeInfoDetail detail = new UserCardTypeInfoDetail();
			BeanUtils.copyProperties(uctie, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public String createUserCard(String cardNumber, Long cardTypeId, Date beginDateTime, Date endDateTime) {
		List<UserCardInfoEntity> list = userCardInfoService.inquireUserCardInfoList(cardNumber);
		if (!list.isEmpty()) {
			throw new BusinessException("该卡已存在，不能重复添加!");
		}

		UserCardTypeInfoEntity cardType = userCardTypeService.inquireCardTypeDetail(cardTypeId);
		UserCardInfoEntity card = new UserCardInfoEntity();
		card.setCardTypeId(cardType.getCardTypeId());
		card.setCardNumber(cardNumber);
		card.setBeginDateTime(beginDateTime);
		card.setEndDateTime(endDateTime);
		card.setCardCreator(FinanceSessionContext.getAccountFullName());
		card.setCardCreateDateTime(DateUtil.now());
		card.setCardStatus(CardStatusEnum.UNUSED);

		return userCardInfoService.createUserCardInfo(card).toString();
	}

	@Override
	public void enableCard(Long userCardId) {
		UserCardInfoEntity card = userCardInfoService.inquireUserCardInfoDetail(userCardId);
		card.setCardStatus(CardStatusEnum.USED);
		userCardInfoService.updateUserCardInfo(card);
	}

	@Override
	public void disableCard(Long userCardId) {
		UserCardInfoEntity card = userCardInfoService.inquireUserCardInfoDetail(userCardId);
		card.setCardStatus(CardStatusEnum.STOP);
		userCardInfoService.updateUserCardInfo(card);
	}

	@Override
	public UserCardInfoDetail inquireUserCardInfo(Long userCardId) {
		UserCardInfoEntity entity = userCardInfoService.inquireUserCardInfoDetail(userCardId);

		UserCardTypeInfoEntity cardType = userCardTypeService.inquireCardTypeDetail(entity.getCardTypeId());
		UserCardTypeInfoDetail typeDetail = new UserCardTypeInfoDetail();
		BeanUtils.copyProperties(cardType, typeDetail);

		UserCardInfoDetail detail = new UserCardInfoDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setCardStatus(entity.getCardStatus().ordinal());
		detail.setCardTypeName(cardType.getCardTypeName());
		detail.setUserCatdType(typeDetail);
		return detail;
	}

	@Override
	public UserCardInfoDetail inquireUserCardInfoDetailFromEnterpriseId() {
		EnterpriseEntity enterprise = enterpriseService.inquireEnterpriseFromAccountId(FinanceSessionContext.getAccountId());
		UserCardInfoEntity entity = userCardInfoService.inquireUserCardInfoDetailFromEnterpriseId(enterprise.getEnterpriseId());
		UserCardTypeInfoEntity cardType = new UserCardTypeInfoEntity();
		if (entity != null) {
			cardType = userCardTypeService.inquireCardTypeDetail(entity.getCardTypeId());
		}
		UserCardTypeInfoDetail typeDetail = new UserCardTypeInfoDetail();
		BeanUtils.copyProperties(cardType, typeDetail);

		UserCardInfoDetail detail = new UserCardInfoDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setCardStatus(entity == null ? null : entity.getCardStatus().ordinal());
		detail.setCardTypeName(cardType.getCardTypeName());
		detail.setUserCatdType(typeDetail);

		return detail;
	}

	@Override
	public PageList<UserCardInfoDetail> inquireUserCardPageList(PageCriteria page) {
		PageList<UserCardInfoEntity> pages = userCardInfoService.inquireUserCardInfoPageList(page);
		PageList<UserCardInfoDetail> results = new PageList<UserCardInfoDetail>(page, pages.getTotalRecordCount());
		for (UserCardInfoEntity ucie : pages) {
			UserCardTypeInfoEntity cardType = userCardTypeService.inquireCardTypeDetail(ucie.getCardTypeId());
			UserCardInfoDetail detail = new UserCardInfoDetail();
			BeanUtils.copyProperties(ucie, detail);
			detail.setCardStatus(ucie.getCardStatus().ordinal());
			detail.setCardTypeName(cardType.getCardTypeName());
			results.add(detail);
		}
		return results;
	}

	@Override
	public String createUserActiveCardInfo(String cardNumber, String cardFrontFile, String cardBackFile, Long enterpriseId) {
		List<UserCardInfoEntity> userCards = userCardInfoService.inquireUserCardInfoList(cardNumber);
		if (userCards.isEmpty()) {
			throw new BusinessException("该卡不存在！");
		}
		if (CardStatusEnum.USED != userCards.get(0).getCardStatus()) {
			throw new BusinessException("该卡已被使用！");
		}
		EnterpriseEntity enterprise = null;
		if (null != enterpriseId) {
			enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		} else {
			enterprise = enterpriseService.inquireEnterpriseFromAccountId(FinanceSessionContext.getAccountId());
		}
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
		if (null == grade) {
			throw new BusinessException("还未认证的企业不能开卡！");
		}
		UserActiveCardInfoEntity entity = new UserActiveCardInfoEntity();
		entity.setCardNumber(cardNumber);
		entity.setCardBackFile(cardBackFile);
		entity.setCardFrontFile(cardFrontFile);
		entity.setEnterpriseName(enterprise.getEnterpriseName());
		entity.setEnterpriseId(enterprise.getEnterpriseId());
		entity.setAuditState(AuditStateEnum.UNAUDIT);
		entity.setOperationDateTime(DateUtil.now());
		entity.setOperator(FinanceSessionContext.getAccountFullName());
		userActiveCardInfoService.createUserActiveCardInfo(entity);
		return entity.getActiceCardId().toString();
	}

	@Override
	@Transactional
	public void auditUserActiveCardInfo(Long acticeCardId, Integer auditState, String auditRemark) {
		UserActiveCardInfoEntity entity = userActiveCardInfoService.inquireUserActiveCardInfo(acticeCardId);
		entity.setAuditDateTime(DateUtil.now());
		entity.setAuditor(FinanceSessionContext.getAccountFullName());
		entity.setAuditorId(FinanceSessionContext.getAccountId());
		entity.setAuditRemark(auditRemark);
		entity.setAuditState(AuditStateEnum.valueOf(auditState));
		userActiveCardInfoService.updateUserActiveCardInfo(entity);

		if (AuditStateEnum.PASS == entity.getAuditState()) {
			UserCardInfoEntity userCard = userCardInfoService.inquireUserCardInfoList(entity.getCardNumber()).get(0);
			userCard.setCardBackFile(entity.getCardBackFile());
			userCard.setCardFrontFile(entity.getCardBackFile());
			userCard.setCardDistributeDateTime(DateUtil.now());
			userCard.setCardDistributeOperator(FinanceSessionContext.getAccountFullName());
			userCard.setCardStatus(CardStatusEnum.AGREE);
			userCard.setCardStatusChangeReason("开卡");
			userCard.setEnterpriseName(entity.getEnterpriseName());
			userCard.setEnterpriseId(entity.getEnterpriseId());
			userCardInfoService.updateUserCardInfo(userCard);

			UserCardTypeInfoEntity cardType = userCardTypeService.inquireCardTypeDetail(userCard.getCardTypeId());
			EnterpriseGradeEvaluationEntity egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluation(entity.getEnterpriseId());
			egee.setInterestRate(cardType.getRateDiscount());
			egee.setPenalInterest(cardType.getPunishDiscount());
			enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(egee);
		}
	}

	@Override
	public UserActiveCardInfoDetail inquireUserActiveCardInfoDetail(Long acticeCardId) {
		UserActiveCardInfoEntity entity = userActiveCardInfoService.inquireUserActiveCardInfo(acticeCardId);
		UserActiveCardInfoDetail detail = new UserActiveCardInfoDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setAuditState(entity.getAuditState().ordinal());
		return detail;
	}

	@Override
	public PageList<UserActiveCardInfoDetail> inquireUserActiveCardInfoPageList(Integer auditState, PageCriteria page) {
		PageList<UserActiveCardInfoEntity> pages = userActiveCardInfoService.inquireUserActiveCardInfoPageList(auditState, page);
		PageList<UserActiveCardInfoDetail> results = new PageList<UserActiveCardInfoDetail>(page, pages.getTotalRecordCount());
		for (UserActiveCardInfoEntity uacie : pages) {
			UserActiveCardInfoDetail detail = new UserActiveCardInfoDetail();
			BeanUtils.copyProperties(uacie, detail);
			detail.setAuditState(uacie.getAuditState().ordinal());
			results.add(detail);
		}
		return results; 
	}

	@Override
	@Transactional
	public void changeEmployeePosition(Long orgId, Long empId, String position) {
		DetachedCriteria criteria = DetachedCriteria.forClass(OrgREmpEntity.class);
		criteria.add(Restrictions.eq("empId", empId));
		List<OrgREmpEntity> es = PersistUtil.get(criteria);
		if (es != null && !es.isEmpty()) {
			OrgREmpEntity entity = (OrgREmpEntity) PersistUtil.get(criteria).get(0);
			entity.setOrgId(orgId);
			entity.setPosition(position);
			PersistUtil.update(entity);
		} else {
			OrgREmpEntity entity = new OrgREmpEntity();
			entity.setOrgId(orgId);
			entity.setPosition(position);
			entity.setEmpId(empId);
			entity.setCreateDate(DateUtil.now());
			entity.setTenantId(1L);
			PersistUtil.insert(entity);
		}
	}

	@Override
	@Transactional
	public String createDataSource(String dataSource) {
		DataSourceEntity entity = new DataSourceEntity();
		entity.setDataSource(dataSource);
		return dataSourceService.createDataSoruce(entity).toString();
	}

	@Override
	@Transactional
	public void updateDataSource(Long dataSourceId, String dataSource) {
		DataSourceEntity entity = dataSourceService.inquireDataSource(dataSourceId);
		entity.setDataSource(dataSource);
		dataSourceService.updataDataSource(entity);
	}

	@Override
	@Transactional
	public void disableDataSource(Long dataSourceId) {
		DataSourceEntity entity = dataSourceService.inquireDataSource(dataSourceId);
		entity.setEnabled(Boolean.FALSE);
		dataSourceService.updataDataSource(entity);
	}

	@Override
	@Transactional
	public void enableDataSource(Long dataSourceId) {
		DataSourceEntity entity = dataSourceService.inquireDataSource(dataSourceId);
		entity.setEnabled(Boolean.TRUE);
		dataSourceService.updataDataSource(entity);
	}

	@Override
	@Transactional
	public void deleteDataSource(Long dataSourceId) {
		dataSourceService.deleteDataSource(dataSourceId);
	}

	@Override
	public DataSourceDetail inquireDataSourceDetail(Long dataSourceId) {
		DataSourceEntity entity = dataSourceService.inquireDataSource(dataSourceId);
		DataSourceDetail detail = new DataSourceDetail();
		BeanUtils.copyProperties(entity, detail);
		return detail;
	}

	@Override
	public PageList<DataSourceDetail> inquireDataSourcePageList(PageCriteria page) {
		PageList<DataSourceEntity> list = dataSourceService.inquireDataSourcePageList(page);
		PageList<DataSourceDetail> results = new PageList<>(page, list.getTotalRecordCount());
		for (DataSourceEntity dse : list) {
			DataSourceDetail detail = new DataSourceDetail();
			BeanUtils.copyProperties(dse, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public List<DataSourceDetail> inquireDataSourceList() {
		List<DataSourceEntity> list = dataSourceService.inquireDataSourceList();
		List<DataSourceDetail> results = new ArrayList<>();
		for (DataSourceEntity dse : list) {
			DataSourceDetail detail = new DataSourceDetail();
			BeanUtils.copyProperties(dse, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public String getRandomCode() {
		FinanceQRCodeEntity entity = new FinanceQRCodeEntity();
		entity.setRandomCode(UUID.randomUUID().toString());
		entity.setScan(Boolean.FALSE);
		financeQRCodeService.createFinanceQRCode(entity);
		return entity.getRandomCode();
	}

	@Override
	public void registRandomCode(String randomCode) {
		FinanceQRCodeEntity entity = financeQRCodeService.inquireFinanceQRCode(randomCode);
		if (entity == null || entity.getScan()) {}
		entity.setScan(Boolean.TRUE);
		entity.setSessionUuid(FinanceSessionContext.getSessionUuid());
		financeQRCodeService.updateFinanceQECode(entity);
	}

	@Override
	public String getSid(String randomCode) {
		FinanceQRCodeEntity entity = financeQRCodeService.inquireFinanceQRCode(randomCode);
		String sid = entity.getSessionUuid();
		return sid;
	}

	@Override
	public void passData(String randomCode, String data) {
		FinanceQRCodeEntity entity = financeQRCodeService.inquireFinanceQRCode(randomCode);
		entity.setSessionUuid(data);
		financeQRCodeService.updateFinanceQECode(entity);
	}

	@Override
	public String getPassedData(String randomCode) {
		FinanceQRCodeEntity entity = financeQRCodeService.inquireFinanceQRCode(randomCode);
		String data = entity.getSessionUuid();
		return data;
	}

	@Override
	public List<InquireFileOutput> inquireFiles(String fileUuids) {
		InquireFileAction inquireFileAction = ComponentFactory.loadClass(InquireFileAction.class);
		List<InquireFileOutput> files = new ArrayList<>();
		for (String fileUuid : fileUuids.split(",")) {
			if (StringUtil.isBlank(fileUuid)) {
				continue;
			}
			DeleteFileActionInput uuid=new DeleteFileActionInput();
			uuid.setFileUuid(fileUuid);
			InquireFileOutput inquireFileOutput = inquireFileAction.inquireFile(uuid);
			files.add(inquireFileOutput);
		}

		return files;
	}

	@Override
	public UpdateInfo getUpdateInfo() {
		UpdateInfo ui = new UpdateInfo();
		ui.setForced(ConfigPropertites.getProperties("app.android.forced"));
		ui.setIgnore(ConfigPropertites.getProperties("app.android.ignore"));
		ui.setOriginal(String.valueOf(ConfigPropertites.getProperties("app.android.original")));
		ui.setUpdateContent(String.valueOf(ConfigPropertites.getProperties("app.android.updateContent")));
		ui.setUpdateTime(Long.valueOf(ConfigPropertites.getProperties("app.android.updateTime")));
		ui.setUpdateUrl(String.valueOf(ConfigPropertites.getProperties("app.android.updateUrl")));
		ui.setVersionCode(Integer.valueOf(ConfigPropertites.getProperties("app.android.versionCode")));
		ui.setVersionName(String.valueOf(ConfigPropertites.getProperties("app.android.versionName")));
		return ui;
	}

	@Override
	@Transactional
	public void logout1() {
		AccountSessionEntity ase = PersistUtil.get(AccountSessionEntity.class, FinanceSessionContext.getSessionUuid());
		if (ase == null) {
			throw new BusinessException("UNLOGIN", "该账号已再其他设备退出登录！");
		}
		AccountTerminalEntity ate = accountTerminalService.inquireAccountTerminal(ase.getAccountId());
		if (ate != null) {
			accountTerminalService.deleteAccountTerminal(ase.getAccountId());
		}
		PersistUtil.delete(ase);

	}

	@Override
	@Transactional
	public SessionDetail loginWithoutPassword(String userName) {
		LoginActionFinanceImpl loginCommand = new LoginActionFinanceImpl();
		SessionDetail detail = new SessionDetail();
		AccountNameEntity accountName = null;
		String appKey = "";
		Long tenantId = 0L;
		if ("admin".equals(userName)) {
			accountName = accountService.inquireAccountName(userName);
			appKey = "FINANCE-PLATFORM-WEB";
			detail.setAccountType(1);
			tenantId = 1L;
		} else if (userName.indexOf("@") < 0) {
			accountName = accountService.inquireAccountName(userName);
			appKey = "FINANCE-ENTERPRISE-WEB";
			detail.setAccountType(0);
		} else {
			accountName = accountService.inquireAccountName(userName.substring(0, userName.indexOf('@') + 1) + 1);
			appKey = "FINANCE-PLATFORM-WEB";
			detail.setAccountType(1);
			tenantId = 1L;
		}
		DetachedCriteria criteria = DetachedCriteria.forClass(AccountSessionEntity.class);
		if (accountName == null) {
			throw new BusinessException("账号不存在");
		}
		criteria.add(Restrictions.eq("accountId", accountName.getAccountId()));
		criteria.add(Restrictions.eq("appUuid", appKey));
		List<AccountSessionEntity> list = PersistUtil.get(criteria);
		if (list == null || list.isEmpty()) {
			AccountSessionEntity ase = new AccountSessionEntity();
			ase.setSessionUuid(UuidUtil.randomUUID());
			ase.setAccountId(accountName.getAccountId());
			ase.setTenantId(tenantId);
			PersistUtil.insert(ase);
			loginCommand.afterLogin1(ase.getSessionUuid(), ase.getAccountId(), appKey, ase);
			detail.setSessionUuid(ase.getSessionUuid());
			ase.setAppUuid(appKey);
			ase.setCreateDate(DateUtil.now());
			ase.setExpireDate(DateUtil.tenYearsLater());
			PersistUtil.update(ase);
		} else {
			detail.setSessionUuid(list.get(0).getSessionUuid());
		}
		return detail;
	}

	@Override
	public String loginByUserId(String userId, String appKey) {
		FingerTrunkAccountMappingEntity ftame = fingerTrunkAccountMappingService.inquireFingerTrunkAccountMappingDetail(userId);
		if (ftame == null) {
			throw new BusinessException("账号不存在");
		}
		DetachedCriteria criteria = DetachedCriteria.forClass(AccountSessionEntity.class);
		criteria.add(Restrictions.eq("accountId", ftame.getFinanceAccountId()));
		criteria.add(Restrictions.eq("appUuid", appKey));
		List<AccountSessionEntity> list = PersistUtil.get(criteria);
		if (list == null || list.isEmpty()) {
			AccountSessionEntity ase = new AccountSessionEntity();
			ase.setSessionUuid(UuidUtil.randomUUID());
			ase.setAccountId(ftame.getFinanceAccountId());
			PersistUtil.insert(ase);
		}
		return list.get(0).getSessionUuid();
	}

	@Override
	public Long createRankingList(String name) {
		try {
			RankingListEntity entity = new RankingListEntity();
			entity.setName(URLEncoder.encode(name, "utf-8"));
			logger.info("name:" + URLEncoder.encode(name, "utf-8"));
			return rankingListService.createRankingList(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void updateRankingList(Long rankingId, Integer time, Integer level) {
		logger.info("name:" + rankingId + "time:" + time +"level:" + level);
		RankingListEntity entity = rankingListService.inquireRanking(rankingId);
		logger.info(String.valueOf(entity == null));
		logger.info(entity.toString());
		if (entity.getTime() == null || entity != null && time <= entity.getTime()) {
			entity.setTime(time);
			entity.setLevel(level);
			rankingListService.updateRankingList(entity);
		}
	}

	@Override
	public List<RankingListDetail> inquireRankingList() {
		try {
			List<RankingListEntity> list = rankingListService.inquireRankingList();
			List<RankingListDetail> results = new ArrayList<>();
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getTime() == null || list.get(i).getTime() == 0) {
					continue;
				}
				RankingListDetail detail = new RankingListDetail();
				BeanUtils.copyProperties(list.get(i), detail);
				detail.setOrder(i+1);
				detail.setName(URLDecoder.decode(list.get(i).getName(), "utf-8"));
				results.add(detail);
			}
			return results;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@Transactional
	public String createFinanceLetter(String userName, String title, String content, String followType, String followId) {
		AccountNameEntity accountName = null;
		if ("admin".equals(userName)) {
			accountName = accountService.inquireAccountName(userName);
		} else if (userName.indexOf("@") < 0) {
			accountName = accountService.inquireAccountName(userName);
		} else {
			accountName = accountService.inquireAccountName(userName.substring(0, userName.indexOf('@') + 1) + 1);
		}
		if (accountName == null) {
			throw new BusinessException("账号不存在");
		}
		
		FinanceLetterEntity letter = new FinanceLetterEntity();
		letter.setTitle(title);
		letter.setContent(content);
		letter.setReceiverAccountId(accountName.getAccountId());
		if (StringUtil.isNotBlank(followId)) {
			letter.setFollowId(followId);
		}
		if (StringUtil.isNotBlank(followType)) {
			letter.setFollowType(Integer.valueOf(followType));
		}
		financeLetterService.createFinanceLetter(letter);
		return "";
	}

	@Override
	public PageList<FinanceLetterDetail> inquireFinanceLetterPageList(Integer letterType, Integer readFlag,
			PageCriteria page) {
		Boolean f = null;
		if (null == readFlag) {
			
		}else if (1 == readFlag) {
			f = Boolean.FALSE;
		} else if (2 == readFlag) {
			f = Boolean.TRUE;
		}
		PageList<FinanceLetterEntity> pages = financeLetterService.inquireFinanceLetterPageList(FinanceSessionContext.getAccountId(), letterType, f, page);
		PageList<FinanceLetterDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (FinanceLetterEntity fle : pages) {
			FinanceLetterDetail detail = new FinanceLetterDetail();
			BeanUtils.copyProperties(fle, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public List<FinanceLetterDetail> inquireFinanceLetterList(Integer letterType, Integer readFlag) {
		Boolean f = null;
		if (1 == readFlag) {
			f = Boolean.FALSE;
		} else if (2 == readFlag) {
			f = Boolean.TRUE;
		}
		List<FinanceLetterEntity> list = financeLetterService.inquireFinanceLetterList(FinanceSessionContext.getAccountId(), letterType, f);
		List<FinanceLetterDetail> results = new ArrayList<>();
		for (FinanceLetterEntity fle : list) {
			FinanceLetterDetail detail = new FinanceLetterDetail();
			BeanUtils.copyProperties(fle, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public String createFinanceFilesNorm(String normFileName, Integer isNotNull, Integer isSign, Integer filesType) {
		FinanceFilesNormEntity entity = new FinanceFilesNormEntity();
		entity.setNormFileName(normFileName);
		entity.setIsNotNull(isNotNull);
		entity.setIsSign(isSign);
		entity.setCreator(FinanceSessionContext.getAccountFullName());
		entity.setFilesType(filesType);
		financeFilesNormService.createFinanceFilesNorm(entity);
		return entity.getNormId().toString();
	}
	
	@Override
	public void deleteFinanceFilesNorm(Long normId) {
		financeFilesNormService.deleteFinanceFilesNorm(normId);
	}

	@Override
	public PageList<FinanceFilesNorm> inquireFinanceFilesNormPageList(Integer filesType, PageCriteria page) {
		PageList<FinanceFilesNormEntity> pages = financeFilesNormService.inquireFinanceFilesNormPageList(filesType, page);
		PageList<FinanceFilesNorm> results = new PageList<>(page, pages.getTotalRecordCount());
		for (FinanceFilesNormEntity ffne : pages) {
			FinanceFilesNorm detail = new FinanceFilesNorm();
			BeanUtils.copyProperties(ffne, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public List<FinanceFilesNorm> inquireFinanceFilesNormList() {
		List<FinanceFilesNormEntity> pages = financeFilesNormService.inquireFinanceFilesNormList();
		List<FinanceFilesNorm> results = new ArrayList<>();
		for (FinanceFilesNormEntity ffne : pages) {
			FinanceFilesNorm detail = new FinanceFilesNorm();
			BeanUtils.copyProperties(ffne, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public void testUpload(String path) {
		TransferServiceImpl transferService = new TransferServiceImpl();
		InputStream is = HttpUtils.returnBitMap(path);
		FileEntry fe = transferService.uploadFile("货物照片", is);
		System.out.println(fe.getFileUuid());
	}

	@Override
	@Transactional
	public void initWarehouseId() {
		List<ContainerInventoryEntity> cies = containerInventoryService.inquireInboundList();
		for (ContainerInventoryEntity cie : cies) {
			String url = ConfigPropertites.getProperties("finance.changeLocationToWarehouse.service");
			Map<String, String> params = new HashMap<>();
			params.put("locationId", cie.getLocationId());
			String responseText = HttpClientHelper.post(url, params);
			logger.info("url:" + url);
			logger.info("params:" + params);
			logger.info("responseText:" + responseText);

			ChangeLocationResult result = JSON.toBean(responseText, ChangeLocationResult.class);
			if ("success".equals(result.getStatus())) {
				cie.setWarehouseId(result.getResult());
				containerInventoryService.updateContainerInventory(cie);
			}
		}
		
		List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(null, null);
		for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
			String url = ConfigPropertites.getProperties("finance.changeLocationToWarehouse.service");
			Map<String, String> params = new HashMap<>();
			params.put("locationId", pbwe.getLocationId());
			String responseText = HttpClientHelper.post(url, params);
			logger.info("url:" + url);
			logger.info("params:" + params);
			logger.info("responseText:" + responseText);

			ChangeLocationResult result = JSON.toBean(responseText, ChangeLocationResult.class);
			if ("success".equals(result.getStatus())) {
				pbwe.setWarehouseId(result.getResult());
				pickupBulkstockWarehouseService.updatePickupBulkstockWarehouse(pbwe);
			}
		}
	}

	@Override
	public ShipInfo inquireShipInfo(String caseNumber, String waybillNumber) {
		String url = ConfigPropertites.getProperties("finance.getContainerlocaiton.service");
		Map<String, String> params = new HashMap<>();
		params.put("ContainerNo", caseNumber);
		params.put("BillNo", waybillNumber);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);
		ShipInfo result = JSON.toBean(responseText, ShipInfo.class);
		if (result == null) {
			throw new BusinessException("无信息");
		}
		return result;
	}
}